package com.thinkcoder.aspect;

import com.thinkcoder.entity.UserHit;
import com.thinkcoder.model.enums.UserHitEnum;
import com.thinkcoder.service.ZsetService;
import com.thinkcoder.service.impl.ZsetSerivceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Order(1)
public class UserHitAspect {

    @Autowired
    private ZsetService zsetSerivce;

    @Pointcut(value = "execution(* com.*.controller.*.*(..))")
    public void hitPointCut(){ }

    @Around(value = "hitPointCut()")
    public Object hitAround(ProceedingJoinPoint joinPoint) throws Throwable{

        //从请求头中拿到请求的uri
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestURI = request.getRequestURI();

        //判断是否是需要统计的uri
        boolean b = UserHitEnum.compareUri(requestURI);
        if(b){
            //如果是则向redis增加数据
            UserHit hit = new UserHit();
            UserHitEnum userHit = UserHitEnum.getUserHit(requestURI);
            hit.setModuleCode(userHit.getModuleCode());
            hit.setModuleName(userHit.getModuleName());
            zsetSerivce.add(hit);
        }
        Object proceed = joinPoint.proceed();
        return proceed;
    }
}
